package neu.edu.vn.appmusic.ui;

import java.util.ArrayList;

import neu.edu.vn.appmusic.R;
import neu.edu.vn.appmusic.adapter.SongAdapter;
import neu.edu.vn.appmusic.common.Constant;
import neu.edu.vn.appmusic.object.Song;
import neu.edu.vn.appmusic.utils.ImageLoadAsyncTask;
import neu.edu.vn.appmusic.utils.ImageUtils;
import neu.edu.vn.appmusic.utils.music.MusicController;
import neu.edu.vn.appmusic.utils.music.MusicService;
import neu.edu.vn.appmusic.utils.music.MusicService.MusicBinder;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class FragmentOnline extends Fragment implements MediaPlayerControl {
	
	//elements of GUI
	private String urlImageMain;
	private String urlImageRightTop;
	private String urlImageRightBottom;
	private ImageView ivMain;
	private ImageView ivImage1;
	private ImageView ivImage2;
	private TextView tvTitle;
	
	private ArrayList<Song> arraySong = new ArrayList<Song>();
	private SongAdapter songAdapter;
	private ListView lvSong;
	
	//play music 
	private MusicService musicSrv;
	private Intent playIntent;
	private boolean musicBound=false;
	private MusicController controller;
	//activity and playback pause flags
	private boolean paused=false, playbackPaused=false;
	//connect to the service
	private ServiceConnection musicConnection = new ServiceConnection(){
	 
	  @Override
	  public void onServiceConnected(ComponentName name, IBinder service) {
	    MusicBinder binder = (MusicBinder)service;
	    //get service
	    musicSrv = binder.getService();
	    //pass list
	    musicSrv.setList(arraySong);
	    musicBound = true;
	  }
	 
	  @Override
	  public void onServiceDisconnected(ComponentName name) {
	    musicBound = false;
	  }
	};
	
	
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_online, container, false);
		return rootView;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
//		setTitleFragmemt();
		initGUIFragment();
		loadContentFromServer();
		setController();
		if (playIntent == null) {
			playIntent = new Intent(getActivity(), MusicService.class);
			getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
			getActivity().startService(playIntent);
		}
	}
	
	public void setTitleFragmemt(){
		Bundle args = new Bundle();
		args.putString("title", getResources().getString(R.string.fragment_name_online));
		this.setArguments(args);
	}
	
	public void initGUIFragment(){
		ivMain = (ImageView) getView().findViewById(R.id.ivMain);
		ivImage1 = (ImageView) getView().findViewById(R.id.ivImage1);
		ivImage2 = (ImageView) getView().findViewById(R.id.ivImage2);
		songAdapter = new SongAdapter(getActivity(), R.layout.item_list_row, arraySong);
		lvSong = (ListView) getView().findViewById(R.id.lvNewMusic);
		lvSong.setAdapter(songAdapter);
		lvSong.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				Toast.makeText(getActivity(), "Select text : src: " + arraySong.get(position).getSrc() + " ID : " + id + " Position :" + position, Toast.LENGTH_SHORT).show();
				songPicked(position);
			}
		});
	}
	
	public void loadContentFromServer(){
		//load Image, music song
//		ivMain.setImageResource(R.drawable.bichphuong);
//		ivImage1.setImageResource(R.drawable.vioanh);
//		ivImage2.setImageResource(R.drawable.hongocha);
		//load list song
		RequestQueue queue = Volley.newRequestQueue(getActivity());
		StringRequest request = new StringRequest(Constant.API_GET_MUSIC, new Listener<String>() {

			@Override
			public void onResponse(String result) {
				try {
					JSONObject jsonObject= new JSONObject(result);
					JSONObject jsonResult = jsonObject.getJSONObject("result");
					
					JSONObject jsonImage = jsonResult.getJSONObject("tilte");
					urlImageMain = jsonImage.getString("left");
					urlImageRightTop = jsonImage.getString("right_top");
					urlImageRightBottom = jsonImage.getString("right_bottom");
					new ImageLoadAsyncTask(urlImageMain, ivMain).execute(null, null);
//					ImageUtils.getInstance(getActivity().getApplication().getApplicationContext()).loadImageToImageview(urlImageMain, ivMain);
					ImageUtils.getInstance(getActivity().getApplication().getApplicationContext()).loadImageToImageview(urlImageRightTop, ivImage1);
					ImageUtils.getInstance(getActivity().getApplication().getApplicationContext()).loadImageToImageview(urlImageRightBottom, ivImage2);
//					ivImage1.setImageBitmap(ImageLoadAsyncTask.getBitmapFromURL(urlImageRightTop)); 
					
					JSONArray data = jsonResult.getJSONArray("data");
					Song song;
					for (int i = 0; i < data.length(); i++) {
						JSONObject jsongSong = data.getJSONObject(i);
						song = new Song();
						song.setAuthor(jsongSong.getString("singer"));
						song.setSongName(jsongSong.getString("name"));
						song.setId(jsongSong.getInt("id"));
						song.setSrc(jsongSong.getString("src"));
						song.setDuration(jsongSong.getString("duration"));
						song.setUrlImage(jsongSong.getString("icon_album"));
//						song.setPlayCount(jsongSong.getInt("play_count"));
						arraySong.add(song);
					}
					if(songAdapter != null){
						songAdapter.notifyDataSetChanged();
					}
				} catch (Exception e) {
					Log.e("EXRCEPTION", e.getMessage());
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		queue.add(request);
	}
	
	//user song select
	public void songPicked(int position){
		musicSrv.setSong(position);
		musicSrv.playSong();
		if(playbackPaused){
			setController();
			playbackPaused=false;
		}
		controller.show(0);
	}
	
	@Override
	public boolean canPause() {
		return true;
	}

	@Override
	public boolean canSeekBackward() {
		return true;
	}

	@Override
	public boolean canSeekForward() {
		return true;
	}

	@Override
	public int getAudioSessionId() {
		return 0;
	}

	@Override
	public int getBufferPercentage() {
		return 0;
	}

	@Override
	public int getCurrentPosition() {
		if(musicSrv!=null && musicBound && musicSrv.isPng())
			return musicSrv.getPosn();
		else return 0;
	}

	@Override
	public int getDuration() {
		if(musicSrv!=null && musicBound && musicSrv.isPng())
			return musicSrv.getDur();
		else return 0;
	}

	@Override
	public boolean isPlaying() {
		if(musicSrv!=null && musicBound)
			return musicSrv.isPng();
		return false;
	}

	@Override
	public void pause() {
		playbackPaused=true;
		musicSrv.pausePlayer();
	}

	@Override
	public void seekTo(int pos) {
		musicSrv.seek(pos);
	}

	@Override
	public void start() {
		musicSrv.go();
	}

	//set the controller up
	private void setController(){
		controller = new MusicController(getActivity());
		//set previous and next button listeners
		controller.setPrevNextListeners(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				playNext();
			}
		}, new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				playPrev();
			}
		});
		//set and show
		controller.setMediaPlayer(this);
		controller.setAnchorView(getView().findViewById(R.id.lvNewMusic));
		controller.setEnabled(true);
	}

	private void playNext(){
		musicSrv.playNext();
		if(playbackPaused){ 
			setController();
			playbackPaused=false;
		}
		controller.show(0);
	}

	private void playPrev(){
		musicSrv.playPrev();
		if(playbackPaused){
			setController();
			playbackPaused=false;
		}
		controller.show(0);
	}
	
	@Override
	public void onPause(){
		super.onPause();
		paused=true;
	}

	@Override
	public void onResume(){
		super.onResume();
		if(paused){
			setController();
			paused=false;
		}
	}

	@Override
	public void onStop() {
		controller.hide();
		super.onStop();
	}

	@Override
	public void onDestroy() {
		getActivity().stopService(playIntent);
		musicSrv=null;
		super.onDestroy();
	}
	
}
